// HelpDesk Java Swing Application using MySQL
// University of Cincinnati - Software Engineering EECE 495
// Andrew Yingling, Joseph Shelton, Alex Stephens, Rob Riemens

package helpdesk;

import java.sql.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;


public class LoginForm extends javax.swing.JFrame {
    
    Component frame;
    
    // Creates a new form LoginForm

    public LoginForm() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        usernameEntry = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        loginButton = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();
        messageBox = new javax.swing.JTextField();
        btnRegister = new javax.swing.JButton();
        passwordEntry = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Login"));

        usernameEntry.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                usernameEntryActionPerformed(evt);
            }
        });

        jLabel1.setText("Username:");

        jLabel2.setText("Password:");

        loginButton.setText("Login");
        loginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginButtonActionPerformed(evt);
            }
        });

        exitButton.setText("Exit");
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        messageBox.setEditable(false);

        btnRegister.setText("Register User");
        btnRegister.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRegisterActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                        .add(21, 21, 21)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel2)
                            .add(jLabel1))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(usernameEntry, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
                            .add(passwordEntry)))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                        .add(18, 18, 18)
                        .add(loginButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 93, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(messageBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 41, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(exitButton)))
                .add(22, 22, 22))
            .add(jPanel1Layout.createSequentialGroup()
                .add(70, 70, 70)
                .add(btnRegister)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel1)
                    .add(usernameEntry, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(passwordEntry, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(17, 17, 17)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(loginButton)
                    .add(exitButton)
                    .add(messageBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 13, Short.MAX_VALUE)
                .add(btnRegister)
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(0, 17, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public static int wrongEntry = 0;
    public static int threeTimes = 0;
    
    public void loginTry() throws InterruptedException
    {
        if(wrongEntry == 2)
        {
            threeTimes = 1;
            loginButton.setEnabled(false);
            JOptionPane.showMessageDialog(frame, "You have entered the wrong combination 3 times.\n Please wait 1 minute and try again.");
            (new SwingWorker(){  
                
                @Override
                public Object doInBackground() throws InterruptedException
                {
                    int timer=60;
                    while(timer>0)
                    {
                        Thread.sleep(1000);
                        timer--;
                        messageBox.setText(Integer.toString(timer));
                    } 
                    if(timer == 0)
                    {
                        loginButton.setEnabled(true);
                        threeTimes = 0;
                    }
                    return(null);
                }
            }).execute();
            wrongEntry = 0;
        }
    }
    
    private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginButtonActionPerformed
        String username = "";
        String password = "";
        boolean validLogin = false; 

        username = usernameEntry.getText();
        password = passwordEntry.getText();        
        
        try
        {
            Statement s = HelpDesk.connection.createStatement ();
            s.executeQuery ("SELECT username, password, accountType FROM tblUsers");
            ResultSet rs = s.getResultSet ();
            int count = 0;
            while (rs.next ())
            {
                String strUsername = rs.getString("username");
                String strPassword = rs.getString("password");
                int intAccountType = rs.getInt("accountType");
                //System.out.println ("usernameDB = " + strUsername + ", passwordDB = " + strPassword);
                //System.out.println ("usernameTX = " + username + ", passwordTX = " + password);
                if (username.equals(strUsername) && password.equals(strPassword))
                {
                    validLogin = true;
                    HelpDesk.accountName = strUsername;
                    HelpDesk.accountType = intAccountType;
                }
                ++count;
            }
            rs.close ();
            s.close ();
            
            try 
            {
                loginTry();
            } 
            catch (InterruptedException ex) 
            {
                Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
            }  
        }
        catch (SQLException error)
        {
            System.err.println ("Error message: " + error.getMessage ());
            System.err.println ("Error number: " + error.getErrorCode ());
        }
        
        if (validLogin == true)
        {
            
            System.out.println ("successful login, user acccountType is " + HelpDesk.accountType);
            StudentForm myStudentForm = new StudentForm();
            myStudentForm.setSize(1300, 800);
            myStudentForm.setVisible(true);
            myStudentForm.updateForm();
            this.setVisible(false);
        }
        else
        {
            JOptionPane.showMessageDialog(frame, "The Username & Password combintation is incorrect!");
            wrongEntry++;
            usernameEntry.setText("");
            passwordEntry.setText("");
        }

    }//GEN-LAST:event_loginButtonActionPerformed

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitButtonActionPerformed

    private void usernameEntryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_usernameEntryActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_usernameEntryActionPerformed

    private void btnRegisterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegisterActionPerformed
        
        String username = usernameEntry.getText();
        String password = passwordEntry.getText(); 
        
         // get length of password
        int usernameSize = username.length();
        int pwSize = password.length();
        
        // if the fields are blank don't create a new account
        // username and password need to be global variables
        if(username.equals("") || password.equals(""))
        {           
            JOptionPane.showMessageDialog(null, "Invalid input. Please enter a user name and password.");
        }
        // need to add a check for length as well
        else if(pwSize > 20 || usernameSize > 20)
        {
            JOptionPane.showMessageDialog(null, "Please enter a username and password less than 20 characters long.");   
        }
        else
        {
            //get first and last name of user
            String strFirst = JOptionPane.showInputDialog(null, "Enter your first name: ", "", 1);
            String strLast = JOptionPane.showInputDialog(null, "Enter your last name: ", "", 1);
            
            //create string for VALUES sections of SQL statemenet
            String strValues = "VALUES('" + strFirst + "', '" + strLast + "', '" + username + "', '" + password + "', 0)";
            
            //try to insert username into tblUsers
            try
            {
                Statement s = HelpDesk.connection.createStatement ();
                s.executeUpdate("INSERT INTO tblUsers " + strValues);
                s.close ();
            }
            catch (SQLException error)
            {
                System.err.println ("Error message: " + error.getMessage ());
                System.err.println ("Error number: " + error.getErrorCode ());
            }
            
            //tell user that account was successfully created
            JOptionPane.showMessageDialog(null, "Account created! You may now log in using the Login button");    
        }
    }//GEN-LAST:event_btnRegisterActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new LoginForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnRegister;
    private javax.swing.JButton exitButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton loginButton;
    private javax.swing.JTextField messageBox;
    private javax.swing.JPasswordField passwordEntry;
    private javax.swing.JTextField usernameEntry;
    // End of variables declaration//GEN-END:variables
}
